﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace BackupLibrary
{
    public class Database
    {
        public bool BackupDb(Job job, string fileName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("USE MASTER;\r\n");
            sb.AppendFormat("BACKUP DATABASE {0} \r\n", job.Database);
            sb.AppendFormat("TO DISK = '{0}' \r\n", fileName);
            sb.Append(" WITH FORMAT, \r\n");
            sb.Append(" MEDIANAME = 'Z_SQLServerBackups', ");
            sb.AppendFormat(" NAME = 'Full Backup of {0}'; ", job.Database);

            try
            {
                using (SqlConnection cn = new SqlConnection(CnnString(job)))
                {
                    cn.Open();
                    using (SqlCommand cmd = new SqlCommand(sb.ToString(), cn))
                    {
                        cmd.CommandTimeout = 999999;
                        int sonuc = cmd.ExecuteNonQuery();
                    }
                    cn.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                Settings.Get.AddLog(new LogEntry()
                {
                    Database = "",
                    Date = DateTime.Now,
                    Message = "Yedek hatası \r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.Source + "\r\n",
                    Server = ""
                });
                return false;
            }
        }

        public string[] GetDatabase(Job job)
        {
            List<string> _db = new List<string>();
            using (SqlConnection cn = new SqlConnection(CnnString(job)))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT Name FROM sysdatabases", cn))
                {
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        _db.Add(rd.GetString(0));
                    }
                }
                cn.Close();
            }
            return _db.ToArray();
        }

        private string CnnString(Job job)
        {
            if (job.Security == Job.AutenticationTypes.Sql)
            {
                return String.Format("Data Source={0};Database=master;user id={1};password={2}", job.Server, job.UserName, job.Password);
            }
            else
            {
                return String.Format("Data Source={0};Database=master;Integrated Security=SSPI", job.Server);
            }
        }
    }
}
